# python get-pip.py
# pip install Flask
# pip install Flask-Script
# pip install pandas
import codecs
import hashlib
import json
import os
import traceback
from flask import Flask
from flask import request
from flask_script import Manager

app = Flask(__name__)
manager = Manager(app)

exist_files = set([])
env_dist = os.environ


@app.route("/", methods=["GET"])
def index():
    return "python service works!"


@app.route("/", methods=["POST"])
def execute_file():
    result = {"success": True}
    try:
        file_id = request.form["file_id"]
        variables = request.form["variables"]
        context = json.loads(variables)
        tmpFilePath = env_dist["tmpFilePath"]
        filename = tmpFilePath + "/" + file_id + ".py"
        execfile(filename, context)
        result["result"] = unicode(context["result"])
        return json.dumps(result, False)
    except Exception, e:
        result["success"] = False
        result["errorMsg"] = traceback.format_exc(e)
        return json.dumps(result, False)


@app.route("/execute_script", methods=["POST"])
def execute_script():
    result = {"success": True}
    tmp_file_path = env_dist["tmpFilePath"]

    try:
        script = request.form["script"]
        file_id = hashlib.md5(script.encode("utf-8")).hexdigest();
        filename = tmp_file_path + "/" + file_id + ".py"
        exist = file_id in exist_files
        if not exist:
            exist = os.path.exists(filename)
            if not exist:
                with codecs.open(filename, 'w', encoding='utf-8') as f:
                    f.write(script)
                exist_files.add(file_id)
            else:
                exist_files.add(file_id)
        variables = request.form["variables"]
        context = json.loads(variables)
        execfile(filename, context)
        result["result"] = unicode(context["result"])
        return json.dumps(result, False)
    except Exception, e:
        result["success"] = False
        result["errorMsg"] = traceback.format_exc(e)
        return json.dumps(result, False)


@app.route("/upload", methods=["POST"])
def upload():
    result = {"success": True}
    try:
        script_file = request.form["file"]
        file_id = request.form["file_id"]
        if file_id not in exist_files:
            tmpFilePath = env_dist["tmpFilePath"]
            filename = tmpFilePath + "/" + file_id + ".py"
            with codecs.open(filename, 'w', encoding='utf-8') as f:
                f.write(script_file)
            exist_files.add(file_id)
        return json.dumps(result, False)
    except Exception, e:
        result["success"] = False
        result["errorMsg"] = traceback.format_exc(e)
        return json.dumps(result, False)


@app.route("/isExist", methods=["GET"])
def is_exist():
    result = {"isExist": True}
    try:
        file_id = request.args["file_id"]
        exist = file_id in exist_files
        if not exist:
            tmpFilePath = env_dist["tmpFilePath"]
            filename = tmpFilePath + "/" + file_id + ".py"
            exist = os.path.exists(filename)
        result["isExist"] = exist
        return json.dumps(result, False)
    except Exception, e:
        result["isExist"] = False
        result["errorMsg"] = traceback.format_exc(e)
        return json.dumps(result, False)


if __name__ == "__main__":
    manager.run()
